import {
	drawLine,
	drawCircle,
	clearArc,
	getPosition,
	saveImage,
	pushInStack,
	getUserEvent,
	drawTriangle,
	deawEmptyCycle,
	drawEmptySquare,
	drawEmptyhexagon,
} from '../utils/index';

import { eventEnum } from '../constant/index';

const { isMobile, tapStart, tapMove, tapEnd } = getUserEvent();
let canvas = document.querySelector('#canvas');
let context = canvas.getContext('2d');

let brush = document.querySelector('.brush');
let eraser = document.querySelector('.eraser');
let clean = document.querySelector('.clean');
let save = document.querySelector('.save');
let undo = document.querySelector('.undo');
let redo = document.querySelector('.redo');

let lineSize = 80;
let easerSize = 16;
let lineColor = 'black';
const maxUndoSize = 50;

const undoStack = [];
const redoStack = [];
let curImage = context.getImageData(0, 0, canvas.width, canvas.height);

function undoFn() {
	if (!undoStack.length) {
		return;
	}

	pushInStack(redoStack, curImage, maxUndoSize);
	curImage = undoStack.pop();
	context.putImageData(curImage, 0, 0);
}

function redoFn() {
	if (!redoStack.length) {
		return;
	}

	pushInStack(undoStack, curImage, maxUndoSize);

	curImage = redoStack.pop();
	context.putImageData(curImage, 0, 0);
}

undo.addEventListener(eventEnum.CLICK, undoFn);
redo.addEventListener(eventEnum.CLICK, redoFn);

let isUsing = false;
let clearable = false;

brush.addEventListener(eventEnum.CLICK, () => {
	clearable = false;

	brush.classList.add('active');
	eraser.classList.remove('active');
});

eraser.addEventListener(eventEnum.CLICK, () => {
	clearable = true;

	eraser.classList.add('active');
	brush.classList.remove('active');
});

clean.addEventListener(eventEnum.CLICK, () => {
	context.clearRect(0, 0, canvas.width, canvas.height);
});

save.addEventListener(eventEnum.CLICK, () => {
	saveImage(canvas);
});

let startPoint = {
	x: undefined,
	y: undefined,
};

let endPoint = {
	x: undefined,
	y: undefined,
};

canvas.addEventListener(tapStart, e => {
	isUsing = true;
	// startPoint.x = e.offsetX;
	// startPoint.y = e.offsetY;

	startPoint = getPosition(e, isMobile);

	console.log('startPoint', startPoint);
});

canvas.addEventListener(tapMove, e => {
	if (isUsing) {
		drawEmptyhexagon(e, canvas, context, curImage, startPoint, endPoint, isMobile);
	}
});

canvas.addEventListener(tapEnd, e => {
	isUsing = false;

	undoStack.push(curImage);
	curImage = context.getImageData(0, 0, canvas.width, canvas.height);
});

document.addEventListener(eventEnum.KEY_DOWN, e => {
	if (e.shiftKey && e.ctrlKey && e.code === 'KeyZ') {
		redoFn();
		return;
	}

	if (e.ctrlKey && e.code === 'KeyZ') {
		undoFn();
	}
});
